package it4s.service.api.factory;

import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.PlusScopes;

public class GoogleFactoryInstance extends Factory {

	private Plus plus;
	private GoogleInstance googleInstance;
	
	 /**
	   * Be sure to specify the name of your application. If the application name is {@code null} or
	   * blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
	   */
	  private static final String APPLICATION_NAME = "";
	  
	  /** E-mail address of the service account. */
	  private static final String SERVICE_ACCOUNT_EMAIL = "Enter service account e-mail from "
	      + "https://code.google.com/apis/console/?api=plus into SERVICE_ACCOUNT_EMAIL in "
	      + GoogleFactoryInstance.class;

	@Override
	public GoogleInstance createServiceInstance(IServiceInstance ser) {
		HttpTransport httpTransport = null;
		GoogleCredential credential = null;
		try {
			httpTransport = GoogleNetHttpTransport.newTrustedTransport();
		} catch (GeneralSecurityException | IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

		// Build service account credential.
		try {
			credential = new GoogleCredential.Builder()
					.setTransport(httpTransport)
					.setJsonFactory(jsonFactory)
					.setServiceAccountId("")
					// (SERVICE_ACCOUNT_EMAIL)
					 .setServiceAccountScopes(Collections.singleton(PlusScopes.PLUS_ME))
					.setServiceAccountPrivateKeyFromP12File(
							new File("META-INF/sidlors-501d91096e9e.p12"))
					.build();
		} catch (GeneralSecurityException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// set up global Plus instance
		plus = new Plus.Builder(httpTransport, jsonFactory, credential)
				.setApplicationName(APPLICATION_NAME).build();
		googleInstance=new GoogleInstance();
		googleInstance.setPlus(plus);
		return googleInstance;
	}

}
